package com.houger.ddd.datamanager.manager.context;
import jakarta.annotation.Resource;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class BaseBeanHolder implements ApplicationContextAware {

    @Getter
    private ApplicationContext applicationContext = null;

    private final Map<String, Object> beanMap = new ConcurrentHashMap<>();

    @Resource

    @Override
    public void setApplicationContext(ApplicationContext context) {
        this.applicationContext = context;
    }

    public <T> T getBean(Class<T> clazz) {
        String key = clazz.getName();
        if (beanMap.containsKey(key)) {
            return (T) beanMap.get(key);
        }
        synchronized (beanMap) {
            if (beanMap.containsKey(key)) {
                return (T) beanMap.get(key);
            }
            final T bean = this.getApplicationContext().getBean(clazz);
            beanMap.put(key, bean);
            return bean;
        }
    }

}
